package cn.enaium.message.specific;

import cn.enaium.message.config.JdbcConfig;
import cn.enaium.message.entity.Message;
import cn.enaium.message.repository.MessageRepository;
import cn.enaium.message.repository.MuserRepository;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class SelectMessage {
    Message message = new Message();
    List<Message> list = new ArrayList<>();
    //首页所有留言
    @GetMapping(value = "/selectallmessage")
    public List<Message> SelectAll() {
        //获取SQLSession
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession= jdbcConfig.getSqlSession();
        //获取留言的代理对象
        MessageRepository messageRepository=sqlSession.getMapper(cn.enaium.message.repository.MessageRepository.class);
        list=messageRepository.findAllMessage();
        return getMessagList(jdbcConfig, sqlSession);

    }
    //个人页面，我的留言
    @GetMapping("/selectmymessage")
    public List<Message> SelectMyMessages(String uid){
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession= jdbcConfig.getSqlSession();
        //获取代理对象
        MessageRepository messageRepository=sqlSession.getMapper(cn.enaium.message.repository.MessageRepository.class);
        list=messageRepository.findByIdMessage(Long.parseLong(uid));
        return getMessagList(jdbcConfig, sqlSession);
    }
    @GetMapping("deletemessage")
    public int DelMessage(String id){
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession= jdbcConfig.getSqlSession();
        //获取代理对象
        MessageRepository messageRepository=sqlSession.getMapper(cn.enaium.message.repository.MessageRepository.class);
        int result=messageRepository.deleteMessage(Long.parseLong(id));
        sqlSession.commit();
        jdbcConfig.sqlSessionCommit();
        jdbcConfig.sqlSessionClose();
        sqlSession.close();
        return result;
    }
    private List<Message> getMessagList(JdbcConfig jdbcConfig, SqlSession sqlSession) {
        if (list.size()!=0){
            //关闭Sql链接
            sqlSession.commit();
            jdbcConfig.sqlSessionCommit();
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return list;
        }else {
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return null;
        }
    }
}
